<template>
    <div>
        <breadcrumb></breadcrumb>

        <!-- 列表 -->
        <div class="main">
            <div class="main_head">
                <div class="main_head_left">
                    已选择<span style="color: #1890ff">{{ selectSize }}</span>项
                </div>
                <div class="main_head_right">
                    <button class="addCargoOwner" @click="add()" v-if="permissions.addSysUser.perms != null">
                        <i class="el-icon-plus iconBtn"></i>
                        <span>新增</span>
                    </button>
                    <button class="addCargoOwner" @click="delUsers()" v-if="permissions.remove.perms != null">
                        <i class="iconfont icon-lajitong iconBtn"></i>
                        <span>删除</span>
                    </button>
                </div>
            </div>
            <div class="list">
                <el-table :data="records" style="width: 100%" @selection-change="handleSelectionChange" header-align="left"
                    ref="table">
                    <el-table-column align="left" type="selection" width="50"></el-table-column>
                    <el-table-column align="left" prop="SerialNumber" width="80" label="序号"></el-table-column>
                    <el-table-column align="left" prop="nickName" label="姓名"></el-table-column>
                    <el-table-column align="left" prop="userName" label="账号"></el-table-column>
                    <!-- <el-table-column align="left" prop="password" label="密码" ></el-table-column>-->
                    <el-table-column align="left" prop="phoneNumber" label="联系手机">
                    </el-table-column>
                    <el-table-column align="left" prop="deptName" label="部门">
                        <template slot-scope="scope">
                            <div>{{ scope.row.deptName || '无' }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column align="left" prop="roleName" label="角色"></el-table-column>
                    <el-table-column align="left" prop="createBy" label="操作人"></el-table-column>
                    <el-table-column align="left" prop="createTime" label="操作时间"></el-table-column>
                    <el-table-column align="left" prop="status" label="状态" width="150px">
                        <template slot-scope="scope">
                            <div class="switchBox">
                                <el-switch v-model="scope.row.status" active-text="正常" active-color="#1890FF"
                                    inactive-text="禁用" inactive-color="#CCCFD2" @change="switchChange(scope.row)">
                                </el-switch>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column align="left" label="操作" width="153">
                        <template slot-scope="scope">
                            <div>
                                <el-button type="text" size="small" @click="showAlterDialog(scope.row)">编辑</el-button>
                                <el-button type="text" size="small" @click="showUpPwd(scope.row)">修改密码</el-button>
                                <el-button type="text" size="small" @click="delBtn(scope.row)">删除</el-button>
                                <!-- <el-button type="text" size="small" @click="resetPswd(scope.row.userId)">还原密码</el-button> -->
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 分页 -->
            <div class="paginationBox">
                <el-pagination @current-change="changePages($event)" class="pagination" background
                    layout="slot,prev, pager, next" :current-page.sync="pageCurrent" :total="data.total * 1"
                    :page-size="data.size * 1" :pager-count="5">
                    <template slot>
                        <span style="
                  color: #686868;
                  font-size: 12px;
                  margin-right: 20px;
                  display: inline-block;
                ">
                            共{{ data.total }}条,每页{{ data.size }}条
                        </span>
                    </template>
                </el-pagination>
            </div>
        </div>
        <!-- 新增账号 -->
        <el-dialog class="dialog" :title="dialogTitle" :visible.sync="visibleAddBox" width="458px">
            <el-form ref="addAccountForm" :model="addAccountForm" :rules="addAccountRules" label-width="70px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="姓名" prop="nickName">
                            <el-input v-model="addAccountForm.nickName"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="账号" prop="userName">
                            <el-input v-model="addAccountForm.userName" :disabled="dialogTitle != '新增账号'"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="密码" prop="password" v-if="dialogTitle == '新增账号'" style="margin-bottom: 38px;">
                            <el-input v-model="addAccountForm.password" show-password></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="确认密码" prop="confirmPassword" v-if="dialogTitle == '新增账号'">
                            <el-input v-model="addAccountForm.confirmPassword" show-password></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="联系手机" prop="phoneNumber">
                            <el-input v-model="addAccountForm.phoneNumber"></el-input>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="24">
              <el-form-item label="角色分配" prop="roleId">
                <el-select
                  v-model="addAccountForm.roleId"
                  filterable
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in roleArr"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
                    <el-col :span="24">
                        <el-form-item label="部门" prop="deptId">
                            <el-select v-model="addAccountForm.deptId" filterable placeholder="请选择" style="width: 100%">
                                <el-option v-for="item in deptArr" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" style="display: flex; justify-content: flex-end">
                        <el-button class="cancelBtn" @click="visibleAddBox = false">取 消</el-button>
                        <el-button class="submitBtn" type="primary" @click="submitAccount(dialogTitle)">确 定</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </el-dialog>
        <!-- 修改密码 -->
        <el-dialog class="dialog" title="修改密码" :visible.sync="visibleUpPwd" width="458px">
            <el-form ref="upPwdForm" :model="upPwdForm" :rules="upPwdFormRules" label-width="70px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="旧密码" prop="oldPassword">
                            <el-input v-model="upPwdForm.oldPassword" show-password></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="新密码" prop="newPassword" style="margin-bottom: 38px;">
                            <el-input v-model="upPwdForm.newPassword" show-password></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="确认密码" prop="confirmPassword">
                            <el-input v-model="upPwdForm.confirmPassword" show-password></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" style="display: flex; justify-content: flex-end">
                        <el-button class="cancelBtn" @click="visibleUpPwd = false">取 消</el-button>
                        <el-button class="submitBtn" type="primary" @click="submitAccount('修改密码')">确 定</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </el-dialog>
        <!-- 删除账号 -->
        <!-- <el-dialog class="Deletedialog" title="新增账号" :visible.sync="visibleAddBox" width="458px">
        <div class="Deletedialog_main">
          <i class="iconfontcolor icon-youyichang"></i>
          <div>确定删除该用户吗？</div>
        </div>
        <div style="display: flex;justify-content: flex-end;">
          <el-button class="cancelBtn" @click="visibleAddBox = false">取 消</el-button>
          <el-button class="submitBtn" type="primary">确 定</el-button>
        </div>
      </el-dialog>-->
    </div>
</template>
  
<script>
import breadcrumb from "@/components/breadcrumb";
import httpApi from "@/http";

export default {
    data() {
        var validatePassword = (rule, value, callback) => {
            let rulePassword = /^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*,\.])[0-9a-zA-Z!@#$%^&*,\.]{8,20}$/
            if (value === "") {
                callback(new Error("请输入密码"));
            } else if (!rulePassword.test(this.addAccountForm.password)) {
                callback(new Error('密码至少8位、含一个数字、小写和大写的字母以及特殊字符(!@#$%^&*.)'));
            } else {
                if (this.addAccountForm.password !== "") {
                    this.$refs.addAccountForm.validateField("confirmPassword");
                }
                callback();
            }
        };
        var validateConfirmPassword = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请再次输入密码"));
            } else if (value !== this.addAccountForm.password) {
                callback(new Error("两次输入密码不一致!"));
            } else {
                callback();
            }
        };
        var validateNewPassword = (rule, value, callback) => {
            let rulePassword = /^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*,\.])[0-9a-zA-Z!@#$%^&*,\.]{8,20}$/
            if (value === "") {
                callback(new Error("请输入密码"));
            } else if (!rulePassword.test(this.upPwdForm.newPassword)) {
                callback(new Error('密码至少8位、含一个数字、小写和大写的字母以及特殊字符(!@#$%^&*.)'));
            } else {
                if (this.upPwdForm.newPassword !== "") {
                    this.$refs.upPwdForm.validateField("confirmPassword");
                }
                callback();
            }
        };
        var validateNewConfirmPassword = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请再次输入密码"));
            } else if (value !== this.upPwdForm.newPassword) {
                callback(new Error("两次输入密码不一致!"));
            } else {
                callback();
            }
        };
        return {
            userId: 0, //用户userId
            status: null, //false代表禁用, true代表正常
            selectSize: 0,
            multipleSelection: [],
            visibleAddBox: false,
            visibleUpPwd: false,
            addAccountForm: {
                nickName: "",
                userName: "",
                password: "",
                confirmPassword: "",
                phoneNumber: "",
                roleId: 2,
                // deptId: "",
            },
            upPwdForm: {
                oldPassword: "",
                newPassword: "",
                confirmPassword: "",
            },
            addAccountRules: {
                nickName: [{ required: true, message: "请填写", trigger: "blur" }],
                userName: [{ required: true, message: "请填写", trigger: "blur" }],
                password: [{ required: true, message: "请填写", trigger: "blur" }, { validator: validatePassword, trigger: "blur" },],
                phoneNumber: [{ required: true, message: "请填写", trigger: "blur" }, {
                    pattern: /^1[3-9]\d{9}$/,
                    message: "手机号格式不正确",
                    trigger: "blur",
                },],
                confirmPassword: [{ required: true, message: "请填写", trigger: "blur" }, { validator: validateConfirmPassword, trigger: "blur" }],
                // roleId: [{ required: true, message: '请填写', trigger: 'blur' }],
                // deptId: [{ required: true, message: "请填写", trigger: "blur" }],
            },
            upPwdFormRules: {
                oldPassword: [{ required: true, message: "请填写", trigger: "blur" }],
                newPassword: [{ required: true, message: "请填写", trigger: "blur" }, { validator: validateNewPassword, trigger: "blur" }],
                confirmPassword: [
                    { required: true, message: "请填写", trigger: "blur" }, { validator: validateNewConfirmPassword, trigger: "blur" }
                ],
            },
            options: [],
            data: {},
            pageCurrent: 1, //当前页
            pageSize: 15, //每页10条
            records: [],

            deptArr: [],
            roleArr: [],
            dialogTitle: "新增账号",
            dataInfo: {},
            permissions: {}
        };
    },

    created() {
        this.permissions = JSON.parse(sessionStorage.getItem('permissions'))
    },
    methods: {
        changePages(val) {
            //页码变化时
            this.init(val);
        },
        delUsers() {
            if (this.multipleSelection.length == 0) {
                this.$message.warning('请先选择删除的账号')
                return
            }
            this.$confirm("确定删除该用户吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                if (this.multipleSelection.length > 0) {
                    let userIdsArr = [];
                    this.multipleSelection.map((item) => {
                        userIdsArr.push(item.userId);
                    });
                    let userIds = userIdsArr.join(",");
                    httpApi.basicSettingApi.removeUser({ userIds }).then((res) => {
                        if (res.data.code == 200) {
                            this.$message({
                                type: "success",
                                message: "删除成功!",
                            });
                            this.init(1);
                        }
                    });
                }
            });

            console.log(this.multipleSelection);
        },
        //重置密码   
        resetPswd(userId) {
            this.$confirm('此操作将重置密码, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                httpApi.basicSettingApi.resetPassword({ userId }).then(res => {
                    console.log(res);
                    if (res.data.code == 200) {
                        this.$message.success('重置密码成功')
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消重置'
                });
            });

        },
        showAlterDialog(val) {
            this.visibleAddBox = true;
            this.dialogTitle = "编辑";

            for (let k in val) {
                this.addAccountForm[k] = val[k];
            }
        },
        showUpPwd(val) {
            this.userId = val.userId;
            this.visibleUpPwd = true;
            this.upPwdForm = {
                oldPassword: "",
                newPassword: "",
                confirmPassword: "",
            };
            clear();
        },
        add() {
            this.visibleAddBox = true;
            this.dialogTitle = "新增账号";
            this.clear();
        },
        delBtn(val) {
            this.userId = val.userId;
            this.$confirm("确定删除该用户吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                httpApi.basicSettingApi
                    .removeUser({ userIds: this.userId })
                    .then((res) => {
                        if (res.data.code == 200) {
                            this.$message({
                                type: "success",
                                message: "删除成功!",
                            });
                            this.init(1);
                        }
                    });
            });
        },
        // 清空表单
        clear() {
            this.addAccountForm = {
                nickName: "",
                userName: "",
                password: "",
                confirmPassword: "",
                phoneNumber: "",
                roleId: 2,
                deptId: "",
            };
            this.upPwdForm = {
                oldPassword: "",
                newPassword: "",
                confirmPassword: "",
            };
        },
        handleSelectionChange(val) {
            //复选框点击时
            this.multipleSelection = val;
            this.selectSize = val.length;
        },
        switchChange(val) {
            //状态按钮变化
            let params = {
                userId: val.userId,
            };
            // console.log("参数", params);
            httpApi.basicSettingApi.updateUserStatus(params).then((res) => {
                // console.log("查询结果", res);
                if (res.data.code == 200) {
                    this.$message({
                        type: "success",
                        message: "修改状态成功!",
                    });
                } else {
                    this.$message.error("修改状态失败!");
                    //还原开关按钮状态
                    if (val.status) {
                        val.status = false;
                    } else {
                        val.status = true;
                    }
                }
            });
        },
        submitAccount(type) {
            if (type == "新增账号") {
                this.$refs["addAccountForm"].validate((valid) => {
                    if (valid) {
                        httpApi.basicSettingApi
                            .checkUserName({ userName: this.addAccountForm.userName })
                            .then((res) => {
                                if (res.data.code == 200) {
                                    httpApi.basicSettingApi
                                        .addAccount(this.addAccountForm)
                                        .then((res1) => {
                                            if (res1.data.code == 200) {
                                                this.$message({
                                                    type: "success",
                                                    message: "新增成功!",
                                                });
                                                this.init(1);
                                                this.visibleAddBox = false;
                                                this.$refs["addAccountForm"].resetFields();
                                            }
                                        });
                                } else if (res.data.code == 202) {
                                    this.$message.warning('该账号已存在')
                                }
                            });
                    } else {
                        this.$message.error("信息填写不完整");
                        return false;
                    }
                });
            } else if (type == "编辑") {
                this.$refs["addAccountForm"].validate((valid) => {
                    if (valid) {
                        httpApi.basicSettingApi
                            .updataAccount(this.addAccountForm)
                            .then((res) => {
                                if (res.data.code == 200) {
                                    this.$message({
                                        type: "success",
                                        message: "修改成功!",
                                    });
                                    this.visibleAddBox = false;
                                    this.clear();
                                    this.init(1);
                                }
                            });
                    } else {
                        this.$message.error("信息填写不完整");
                        return false;
                    }
                });
            } else if (type == "修改密码") {
                this.$refs["upPwdForm"].validate((valid) => {
                    if (valid) {
                        this.upPwdForm.userId = this.userId;
                        httpApi.basicSettingApi
                            .updatePassword(this.upPwdForm)
                            .then((res) => {
                                if (res.data.code == 200) {
                                    this.$message({
                                        type: "success",
                                        message: "修改成功!",
                                    });
                                    this.visibleUpPwd = false;
                                    this.init(1);
                                }
                            });
                    }
                });
            }
        },
        init(val) {
            this.pageCurrent = val;
            let params = {
                current: this.pageCurrent,
                size: this.pageSize,
            };
            // console.log("参数", params);
            httpApi.basicSettingApi.getStaffList(params).then((res) => {
                // console.log("查询结果", res);
                if (res.data.code == 200) {
                    this.records = res.data.data.records;
                    this.data = res.data.data;
                    // 前端解决序号
                    // 前端解决序号
                    this.records.forEach((item, i) => {
                        let num = i + 1 + Number(this.pageSize) * (this.pageCurrent - 1);
                        item.SerialNumber = num
                    });
                }
            });
        },
        DeletePromptBox() {
            this.$confirm("确定删除该用户吗？", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.$message({
                        type: "success",
                        message: "删除成功!",
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除",
                    });
                });
        },
        /* 角色数组 */
        getRoleInfo() {
            httpApi.basicSettingApi.getRoles().then((res) => {
                console.log(res);
            });
        },
        //部门数组
        getDeptInfo() {
            httpApi.basicSettingApi.getDepartment().then((res) => {
                if (res.data.code == 200) {
                    console.log(res.data.data);
                    res.data.data.map((item, i) => {
                        this.deptArr.push({ label: item.deptName, value: item.deptId });
                    });
                }
            });
        },
        // 记录滚动距离
        scrollEvent(res) {
            this.$route.meta.scrollTop = res.target.scrollTop
        },
    },
    mounted() {
        this.init(1);
        // this.getRoleInfo();
        this.getDeptInfo();
    },
    activated() {
        //组件激活时监听表格滚动条位置,
        this.$refs.table.bodyWrapper.addEventListener('scroll', this.scrollEvent, false)
        // 激活设置滚动位置
        this.$refs.table.bodyWrapper.scrollTop = this.$route.meta.scrollTop
    },
    beforeRouteLeave(to, from, next) {
        // 为了节省资源，再离开页面的时候关闭对于scroll事件的监听
        this.$refs.table.bodyWrapper.removeEventListener('scroll', this.scrollEvent)
        next()
    },
    components: {
        breadcrumb,
    },
};
</script>
  
<style lang="scss" scoped>
.main {
    width: 100%;
    height: calc(100vh - 127px);
    background-color: #fff;
    padding: 0px 30px 0px 30px;

    .main_head {
        display: flex;
        justify-content: space-between;
        height: 64px;
        align-items: center;

        .main_head_left {
            font-size: 12px;
            color: #262626;
        }

        .main_head_right {
            .addCargoOwner {
                background-color: #1890ff;
                border-radius: 4px;
                height: 32px;
                color: #ffffff;
                font-size: 12px;
                padding: 8px 17px 9px 17px;
                transition: 0.2s;
                cursor: pointer;
                margin-right: 17px;

                .iconBtn {
                    margin-right: 7px;
                    font-size: 12px;
                }

                &:hover {
                    opacity: 0.8;
                }
            }
        }
    }

    .list {
        height: calc(100% - 112px);

        .switchBox {
            display: flex;
            align-items: center;

            .rightText {
                font-size: 12px;
                color: #595959;
            }
        }

        ::v-deep .el-table__body-wrapper {
            height: calc(100vh - 288px);
            overflow-y: scroll;
        }

        // 表头样式
        ::v-deep .el-table__header th {
            background-color: #f0f6fd;
            color: #262626;
            font-size: 12px;
            font-weight: bold;
            text-align: left;
            height: 48px;
            padding: 0;

            // 表 body的td
            ::v-deep .el-table__body td {
                color: #595959;
                font-size: 12px;
            }
        }

        .stateBtns {
            height: 30px;

            ::v-deep .el-button {
                font-size: 12px;
                border: none;
                width: 76px;
                height: 30px;
                margin: 0 auto;
                box-sizing: border-box;
            }

            .icon-dian {
                font-size: 12px;
            }

            .Pass {
                background-color: #ecf5fe;
                color: #1890ff;
                display: flex;
                justify-content: center;
                align-items: center;
                padding: 10px 10px 9px;
            }

            .noPass {
                background-color: #fde8e9;
                color: #f7555d;
                display: flex;
                justify-content: center;
                align-items: center;
            }
        }
    }
}

.dialog {

    // 标题
    ::v-deep .el-dialog__header {
        border-bottom: 1px solid #f0f0f0;
        padding: 15px 20px;
        color: #262626;
        font-size: 14px;
        font-weight: bold;
        height: 50px;
    }

    ::v-deep .el-dialog__title {
        font-size: 14px;
        color: #303133;
        font-weight: bold;
    }

    //关闭图标
    ::v-deep .el-dialog__headerbtn .el-dialog__close {
        font-size: 15px;
    }

    ::v-deep .el-dialog__body {
        padding: 25px 64px 82px;
    }

    //   表格
    ::v-deep .el-form-item__label {
        line-height: 32px;
        font-size: 12px;
        color: #262626;
        padding-top: 4px;
        width: 100%;
    }

    ::v-deep .el-input__inner {
        line-height: 32px;
        height: 32px;
        padding: 0 10px;
    }

    .cancelBtn {
        width: 80px;
        height: 36px;
        border: 1px solid #d9d9d9;
        color: #262626;
        font-size: 12px;
        border-radius: 4px;
        background-color: #fff;
    }

    .submitBtn {
        background-color: #1890ff;
        width: 80px;
        height: 36px;
        color: #fff;
        border-radius: 4px;
        font-size: 12px;
    }

    .inputSelect_left {
        height: 32px;

        ::v-deep .el-input__inner {
            border-radius: 4px 0px 0px 4px;
        }
    }

    .inputSelect_right {
        height: 32px;

        ::v-deep .el-input__inner {
            border-radius: 0px 4px 4px 0px;
            border-left: none;
            background-color: #f5f7fa;
            font-size: 12px;
            color: #606266;
        }
    }

    ::v-deep .el-input__icon {
        line-height: 0;
    }

    ::v-deep .el-form-item__content {
        line-height: 0;
    }

    .notes ::v-deep .el-textarea .el-input__count {
        bottom: 15px;
        color: #c0c4cc;
    }
}

.paginationBox {
    width: 100%;
    background-color: #fff;
    display: flex;
    height: 48px;
    align-items: center;

    .pagination {
        margin-left: auto;
    }
}
</style>
  